package cn.enilu.flash.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class QiNiuYunUtil {

    /** 上传至七牛云服务器文件域名 */
    private static String realName = "http://cdn.bonespace.cn/";

    /** 上传至七牛云服务器accessKey */
    private static String accessKey = "UGPRYgqG1xlLREHLjQ6iyymT6U3tmdwdhsWbvt_k";

    /** 上传至七牛云服务器secretKey */
    private static String secretKey = "_9tGpOE_lpuGpxY8wXWHpMhPupk3OlBJIZwOUo63";

    /** 上传至七牛云服务器空间名称 */
    private static String spaceName = "atbonespace";

    private static Auth auth = Auth.create(accessKey, secretKey);
    /**
     * @author xcq
     * @Description 上传文件并自定义文件名称
     * @des file 文件路径
     * @des key 文件路径
     * @Date: 2021/11/18
     */
    public static String uploadSetName(MultipartFile file, String path, String fileName) throws IOException {

        Auth auth = Auth.create(accessKey, secretKey);
        //指定区域域名(华南)  华北
        Configuration cfg = new Configuration(Region.region1());
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            DefaultPutRet putRet = null;
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 调用put方法上传
            String token = auth.uploadToken(spaceName);
            //判断token
            if (StringUtils.isEmpty(token)) {
                System.out.println("未获取到token，请重试！");
                return null;
            }
            Response res = uploadManager.put(file.getBytes(), path + fileName + "." + fileExt, token);
            //解析上述结果
            putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return realName + putRet.key;
            }
            return null;
        } catch (QiniuException e) {
            Response r = e.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            return r.toString();
        }
    }
}
